package com.example.myapplication;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    public MyAdapter(List<String> bookList) {
        this.bookList = bookList;
    }

    private List<String>bookList;


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_booklist,parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(itemView);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, @SuppressLint("RecyclerView") int position) {
        JSONObject data = null;
        try {
            data = new JSONObject(bookList.get(position));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        holder.textView.setText("书名："+data.optString("name")+"\n作者："+data.optString("author")+"\n出版社："+data.optString("publishing")+"\n出版日期："+data.optString("published"));

        holder.deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除数据中的书籍以及recyclerview里的书籍
                bookList.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeRemoved(position, bookList.size());
            }
        });
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView ;
        Button deleteButton;

        //书籍信息和删除书籍按钮
        public MyViewHolder(View itemView) {
            super(itemView);
            this.textView = itemView.findViewById(R.id.itemviewtext);
            this.deleteButton = itemView.findViewById(R.id.DeleteBook);
        }
    }

}
